package cn.ming.springbootreadwriteseparationdemo.commons.aop;

import cn.ming.springbootreadwriteseparationdemo.commons.DataSourceContextHolder;
import cn.ming.springbootreadwriteseparationdemo.commons.enums.DataSourceTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @ClassName ReadWriteSeparationAop
 * @Description XXX类，用于XXX
 * @Author zhuming
 * @Date 2021-08-01 21:32
 * @Version 1.0.0
 */
@Aspect
@Order(1) //值越小，越优先执行 要优于事务的执行,在启动类中加上了@EnableTransactionManagement
@Component
public class DataSourceAop {
    /**
     * 写数据方法切面，用于切换到主数据库
     */
    @Before("@annotation(cn.ming.springbootreadwriteseparationdemo.commons.annatation.MasterDB)")
    public void masterData() {
        DataSourceContextHolder.setDbContextLocal(DataSourceTypeEnum.MASTER);
    }
    /**
     * 读数据方法切面，用于切换到从数据库
     */
    @Before("@annotation(cn.ming.springbootreadwriteseparationdemo.commons.annatation.SlaveDB)")
    public void slaveData() {
        DataSourceContextHolder.setDbContextLocal(DataSourceTypeEnum.SLAVE);
    }
}
